package com.itisyue.fun.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture;

@Service
public class FileService {
    @Value("${file.base-dir:/}")
    private String baseDir;

    @Async("fileTaskExecutor")
    public CompletableFuture<Resource> readFileAsync(String relativePath) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Path path = Paths.get(baseDir, relativePath).normalize();
                InputStream is = Files.newInputStream(path);
                return new InputStreamResource(is);
            } catch (IOException e) {
                throw new RuntimeException("File read error", e);
            }
        });
    }

    @Async("fileIoExecutor")
    public CompletableFuture<Path> validatePathAsync(String filePath) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Path path = Paths.get(baseDir, filePath).normalize();
                return path;
            } catch (Exception  ex) {
                throw new RuntimeException(ex);

            }
        }, fileIoExecutor.getThreadPoolExecutor());  // 显式绑定自定义线程池[4](@ref)
    }

    @Autowired
    private ThreadPoolTaskExecutor fileIoExecutor;



}